<?php

define('USE_TEMP_DATA_4_KGS2011', true); //是否使用酷公司临时数据(用于紧急情况[true:使用;false:不使用;])


//引入优惠券发放类
include_once 'lib/SendCouponSimple.php';

/**
 *
 * PHP API 活动相关接口
 * @author lid
 */
class ActivityApp extends ApiApp
{
    function __construct()
    {
        $this->ActivityApp();
    }

    function ActivityApp()
    {
        parent::__construct();
        $this->_marketing_activities_apply_mod = & m('marketing_activities_apply');
        //默认填充项
        $this->default_item = array(
            'id' => 'null', //默认图片
            'goods_image' => FILE_SERVER . '/' . 'data/hd_xml/xwyd.jpg', //默认图片
            //'url'=>SITE_URL . '酷公司介绍链接',
        );
    }

    /**
     * 获得优惠券发放状态[针对用户]
     * powered by ww 2011-7-20
     */
    function getCouponSendStatus()
    {
        $coupon_id_list = array(
            '0_5' => array(
                'coupon_id' => BRAND_SHOW_5_YUAN_COUPON_ID,
                'coupon_user_max_num' => 1,
            ),
            '0_150' => array(
                'coupon_id' => BRAND_SHOW_150YUAN_HUASHUO_COUPON_ID,
                'coupon_user_max_num' => 2,
            ),
            '0_300' => array(
                'coupon_id' => BRAND_SHOW_300YUAN_IPAD_COUPON_ID,
                'coupon_user_max_num' => 1,
            ),
            'cool_200_dn' => array(
                'coupon_id' => COOL_200_DN_COUPON_ID,
                'coupon_user_max_num' => 1,
            ),
            'cool_150_sj' => array(
                'coupon_id' => COOL_150_SJ_COUPON_ID,
                'coupon_user_max_num' => 1,
            ),
            'cool_200_xj' => array(
                'coupon_id' => COOL_200_XJ_COUPON_ID,
                'coupon_user_max_num' => 1,
            ),
            'cool_300_ip' => array(
                'coupon_id' => COOL_300_IP_COUPON_ID,
                'coupon_user_max_num' => 1,
            ),
            'cool_100_50' => array(
                'coupon_id' => COOL_100_50_COUPON_ID,
                'coupon_user_max_num' => 1,
            ),
        );
        $coupon_id_query_string = "";
        foreach ($coupon_id_list as $u_key => $item) {
            $coupon_id_query_string .= (empty($coupon_id_query_string) ? "" : ",") . $item['coupon_id'];
        }
        $user_coupon_mod = & m("user_coupon");
        $sql = "
			SELECT c.coupon_id, count(uc.coupon_sn) as cou
			FROM " . DB_PREFIX . "coupon c
			LEFT JOIN " . DB_PREFIX . "coupon_sn cs
			ON cs.coupon_id=c.coupon_id 
			LEFT JOIN " . DB_PREFIX . "user_coupon uc
			ON cs.coupon_sn=uc.coupon_sn 
			WHERE c.coupon_id IN ({$coupon_id_query_string})
			AND uc.user_id={$this->visitor->get('user_id')}
			GROUP BY c.coupon_id";
        $coupon_count_list = $user_coupon_mod->getAll($sql);

        $rst = array();
        foreach ($coupon_id_list as $key => $item2) {
            $rst[$key] = $item2['coupon_user_max_num'];
            foreach ($coupon_count_list as $item1) {
                if ($item1['coupon_id'] == $item2['coupon_id']) {
                    $rst[$key] = $rst[$key] - $item1['cou'];
                    if ($rst[$key] < 0) {
                        $rst[$key] = 0;
                    }
                }
            }
        }
        echo base64_encode(json_encode($rst));
    }

    function getCoolCouponSendStatus()
    {
        $custom_zero_time_u = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $custom_23_time_u = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
        $perday_start_time = $custom_zero_time_u - date('Z');
        $perday_end_time = $custom_23_time_u - date('Z');
        $coupon_id_list = array(

            'cool_100_20' => array(
                'coupon_id' => COOL_100_20_COUPON_ID,
                'coupon_user_max_num' => 1,
            ),
            'cool_100_30' => array(
                'coupon_id' => COOL_100_30_COUPON_ID,
                'coupon_user_max_num' => 1,
            ),
            /*
            'cool_100_50' => array(
                'coupon_id' => COOL_100_50_COUPON_ID,
                'coupon_user_max_num' => 1,
            ),
            */
        );
        $coupon_id_query_string = "";
        foreach ($coupon_id_list as $u_key => $item) {
            $coupon_id_query_string .= (empty($coupon_id_query_string) ? "" : ",") . $item['coupon_id'];
        }
        $user_coupon_mod = & m("user_coupon");
        $sql = "
			SELECT c.coupon_id, count(uc.coupon_sn) as cou
			FROM " . DB_PREFIX . "coupon c
			LEFT JOIN " . DB_PREFIX . "coupon_sn cs
			ON cs.coupon_id=c.coupon_id 
			LEFT JOIN " . DB_PREFIX . "user_coupon uc
			ON cs.coupon_sn=uc.coupon_sn 
			WHERE c.coupon_id IN ({$coupon_id_query_string})
			AND uc.user_id={$this->visitor->get('user_id')}
			AND cs.sent_time > '{$perday_start_time}'
			AND cs.sent_time < '{$perday_end_time}'
			GROUP BY c.coupon_id";
        $coupon_count_list = $user_coupon_mod->getAll($sql);

        $rst = array();
        foreach ($coupon_id_list as $key => $item2) {
            $rst[$key] = $item2['coupon_user_max_num'];
            foreach ($coupon_count_list as $item1) {
                if ($item1['coupon_id'] == $item2['coupon_id']) {
                    $rst[$key] = $rst[$key] - $item1['cou'];
                    if ($rst[$key] < 0) {
                        $rst[$key] = 0;
                    }
                }
            }
        }
        echo base64_encode(json_encode($rst));
    }

    /**
     * 获得商品的销售记录
     * @id string required 商品id 多个id之间使用","分割
     * powered by jeff 2011-5-20
     */
    function apiGetGoodsSaleLog()
    {
        $goods_id = $_REQUEST['id'];

        if (empty($goods_id)) {
            ApiError::showError('goods_id_required', 1);
            return;
        }

        $order_goods_mod =& api_model('ordergoods');
        $sales_list = $order_goods_mod->find(
            array(
                'conditions' => "goods_id = '$goods_id' AND status >= '" . ORDER_ACCEPTED . "'",
                //销售记录为所有已付款状态之后的订单（包括已付款）
                'join' => 'belongs_to_order',
                'fields' => 'buyer_id, buyer_name, add_time, anonymous, goods_id, specification, price, quantity, evaluation, goods_name',
                'count' => true,
                'order' => 'add_time desc',
                'limit' => 10,
            )
        );
        $this->echo_result($sales_list);
    }

    /**
     * 随机获得双色球抽奖号
     * Added By ld 20110623
     */
    function get_double_color_ball_code()
    {
        $hdlyg_zj_mod = & m('hdlyg_zj');
        $code = $hdlyg_zj_mod->get_double_color_ball_code();
        echo $code;
    }

    /**取得酷公司相关展示数据 Begin******************************************************************************************************/
    /**
     * 取得展示数据，并以XML格式返回
     *
     */
    function get_show_xml()
    {
        //参数合法性验证
        if (!isset($_GET['code']) || empty($_GET['code'])) {
            echo ApiError::showError('code_required', 1);
            return;
        }

        $ma_code = $_GET['code'];
        //取得展示数据，并以XML对象返回
        $xml = $this->_get_xml($ma_code);
        //设置输出内容的类型为xml
        header('Content-Type: text/xml;');

        echo $xml->saveXML();

    }

    /**
     * 取得展示数据，并以XML对象返回
     *
     */
    private function _get_xml($ma_code, $default_item = array())
    {
        //默认的占位项
        if (empty($default_item)) {
            $default_item = $this->default_item;
        }

        //展柜信息
        $counter_format_list = array();
        eval("\$counter_format_list = json_decode(" . strtoupper($ma_code) . "_COUNTER_FORMAT,true);");

        $doc = new DOMDocument('1.0', 'utf-8');
        $doc->formatOutput = true;

        $root = $doc->createElement('root'); //新建节点
        $doc->appendChild($root); //加入root为根节点

        //获取相应展示数据
        foreach ($counter_format_list as $key => $counter) {
            //行列
            $rows = $counter['rows'];
            $cols = $counter['cols'];
            //专柜
            $shoppe = $counter['shoppe'];
            //若有专柜
            if (isset($shoppe)) {
                //则循环输出XML
                foreach ($shoppe as $goods_type) {
                    $root->appendChild(
                        $this->_get_goods_list_xml($doc, $ma_code, $key, $goods_type, $rows * $cols, $default_item)
                    );
                }
            } //若没有专柜
            else {
                //则输出XML
                $root->appendChild($this->_get_goods_list_xml($doc, $ma_code, $key, 0, $rows * $cols, $default_item));
            }
        }
        return $doc;
    }

    private function _get_goods_list_xml($doc, $ma_code, $key, $goods_type = '0', $number, $default_item)
    {
        //查询相关详情
        if (!USE_TEMP_DATA_4_KGS2011) {
            //使用kgs数据
            $show_list = $this->_marketing_activities_apply_mod->get_show_list($ma_code, $key, $goods_type, $number);
        } else {
            //使用临时数据
            $show_list = $this->_get_temp_data_4_kgs2011($ma_code, $key, $goods_type, $number);
        }
        //dump($show_list);

        //若数据不足的需要用默认数据填补
        while (count($show_list) < $number) {
            $show_list[] = $default_item;
        }

        $goods_list = $doc->createElement("goods_list");

        //柜台类型
        $counter = $doc->createAttribute('counter');
        $value = $doc->createTextNode($key);
        $counter->appendChild($value);
        $goods_list->appendChild($counter);
        if (!empty($goods_type) || intval($goods_type) === 0) {
            //专柜类型
            $shoppe = $doc->createAttribute('shoppe');
            $value = $doc->createTextNode($goods_type);
            $shoppe->appendChild($value);
            $goods_list->appendChild($shoppe);
        }

        //顺位记录
        $index = 0;

        //组装到xml
        foreach ($show_list as $item) {
            $goods_info = $doc->createElement("goods_info");
            $idx = $doc->createAttribute('index');
            $value = $doc->createTextNode($index);
            $idx->appendChild($value);
            $goods_info->appendChild($idx);

            //商品ID
            $id = $doc->createElement("id");
            if ($item['goods_id']) {
                $value = $doc->createTextNode($item["goods_id"]);
            } else {
                $value = $doc->createTextNode($item['id']);
            }
            $id->appendChild($value);
            $goods_info->appendChild($id);

            //商品名称
            $name = $doc->createElement('name');
            $value = $doc->createTextNode($item['goods_name']);
            $name->appendChild($value);
            $goods_info->appendChild($name);

            //商品价格
            $price = $doc->createElement('price');
            $value = $doc->createTextNode($item['goods_price']);
            $price->appendChild($value);
            $goods_info->appendChild($price);

            //商品图片
            $image = $doc->createElement('image');
            if ($item['goods_id']) {
                $value = "";
                if (isset($item['goods_image']) && !empty($item['goods_image'])) {
                    $value = $doc->createTextNode(FILE_SERVER . '/' . $item['goods_image']);
                } else {
                    $value = $doc->createTextNode('');
                }
            } else {
                $value = $doc->createTextNode($item['goods_image']);
            }
            $image->appendChild($value);
            $goods_info->appendChild($image);

            //商品链接
            $url = $doc->createElement('url');
            $goods_url = "";
            if ($item['goods_id']) {
                $goods_url = SITE_URL . "/index.php?app=goods&id=" . $item['goods_id'];
            } else {
                $goods_url = $item['url'];
            }
            $value = $doc->createCDATASection($goods_url);
            $url->appendChild($value);
            $goods_info->appendChild($url);

            //商品热度
            $views = $doc->createElement('views');
            $value = $doc->createTextNode($item['goods_views']);
            $views->appendChild($value);
            $goods_info->appendChild($views);

            //商品库存
            $stock = $doc->createElement('stock');
            $goods_stock = $item['goods_stock'];
            $value = $doc->createTextNode($goods_stock);
            $stock->appendChild($value);
            $goods_info->appendChild($stock);

            //商品销售状态[0:销售中;1:已卖完;2:未开始;3:已过期;4:已下架;5:已禁售;]
            //商品活动状态
            $goods_status = 0; //0:销售中;
            if (intval($item['closed']) === 1) {
                $goods_status = 5; //5:已禁售;
            } else {
                if (intval($item['if_show']) === 0) {
                    $goods_status = 4; //4:已下架;
                } else {
                    if ($item['end_time'] && $item['end_time'] < gmtime()) {
                        $goods_status = 3; //3:已过期;
                    } else {
                        if ($item['begin_time'] && $item['begin_time'] > gmtime()) {
                            $goods_status = 2; //2:未开始;
                        } else {
                            if ($item['goods_stock'] === '0'
                                || (!empty($item['goods_stock']) && $item['goods_stock'] <= 0)
                            ) {
                                $goods_status = 1; //1:已卖完;
                            }
                        }
                    }
                }
            }
            $status = $doc->createElement('status');
            $value = $doc->createTextNode($goods_status);
            $status->appendChild($value);
            $goods_info->appendChild($status);

            //商品已售
            $sales = $doc->createElement('sales');
            $value = $doc->createTextNode($item['sales']);
            $sales->appendChild($value);
            $goods_info->appendChild($sales);

            $goods_list->appendChild($goods_info);
            $index++;
        }
        //设置node为root子节点
        return $goods_list;
    }

    /**
     * 取得酷公司临时数据
     *
     */
    private function _get_temp_data_4_kgs2011($ma_code, $key, $goods_type, $number)
    {
        //由不同的商品类型返回不同的结果集[0:3c;1:;2:;]
        $goods_id_list = array();
        $goods_image_list = array();
        //取得预置的商品编号及图片
        switch ($goods_type) {
            case 0: //3C
                $goods_id_list = array(
                    '1010000026644',
                    '1010000050265',
                    '1010000032815',
                    '1010000035975',
                    '1010000048126',
                    '1010000046614',
                    '1010000037582',
                    '1010000037574',
                    '1010000029063',
                    '1010000027424',
                );
                $goods_image_list = array(
                    '1010000026644' => 'data/files/cool/3c/11.jpg',
                    '1010000050265' => 'data/files/cool/3c/12.jpg',
                    '1010000032815' => 'data/files/cool/3c/21.jpg',
                    '1010000035975' => 'data/files/cool/3c/22.jpg',
                    '1010000048126' => 'data/files/cool/3c/31.jpg',
                    '1010000046614' => 'data/files/cool/3c/32.jpg',
                    '1010000037582' => 'data/files/cool/3c/41.jpg',
                    '1010000037574' => 'data/files/cool/3c/42.jpg',
                    '1010000029063' => 'data/files/cool/3c/51.jpg',
                    '1010000027424' => 'data/files/cool/3c/52.jpg',
                );
                break;
            case 1: //服装类
                $goods_id_list = array(
                    '1010000048556',
                    '1010000006532',
                    '1010000048118',
                    '1010000048522',
                    '112480',
                    '1010000039928',
                    '1010000046860',
                    '1010000030339',
                    '1010000008868',
                    '1010000048606',
                );
                $goods_image_list = array(
                    '1010000048556' => 'data/files/cool/fs/11.jpg',
                    '1010000006532' => 'data/files/cool/fs/12.jpg',
                    '1010000048118' => 'data/files/cool/fs/21.jpg',
                    '1010000048522' => 'data/files/cool/fs/22.jpg',
                    '112480' => 'data/files/cool/fs/31.jpg',
                    '1010000039928' => 'data/files/cool/fs/32.jpg',
                    '1010000046860' => 'data/files/cool/fs/41.jpg',
                    '1010000030339' => 'data/files/cool/fs/42.jpg',
                    '1010000008868' => 'data/files/cool/fs/51.jpg',
                    '1010000048606' => 'data/files/cool/fs/52.jpg',
                );
                break;
            case 2: //日常用品
                $goods_id_list = array(
                    '1010000042084',
                    '1010000042094',
                    '1010000042082',
                    '1010000042089',
                    '1010000043960',
                    '1010000044596',
                    '1010000042090',
                    '1010000042079',
                    '1010000043959',
                    '1010000043765',
                );
                $goods_image_list = array(
                    '1010000042084' => 'data/files/cool/ry/11.jpg',
                    '1010000042094' => 'data/files/cool/ry/12.jpg',
                    '1010000042082' => 'data/files/cool/ry/21.jpg',
                    '1010000042089' => 'data/files/cool/ry/22.jpg',
                    '1010000043960' => 'data/files/cool/ry/31.jpg',
                    '1010000044596' => 'data/files/cool/ry/32.jpg',
                    '1010000042090' => 'data/files/cool/ry/41.jpg',
                    '1010000042079' => 'data/files/cool/ry/42.jpg',
                    '1010000043959' => 'data/files/cool/ry/51.jpg',
                    '1010000043765' => 'data/files/cool/ry/52.jpg',
                );
                break;
            case 3: //日常家化
                $goods_id_list = array(
                    '1010000022707',
                    '1010000027695',
                    '1010000035956',
                    '1010000046482',
                    '1010000033110',
                    '1010000048597',
                    '1010000044457',
                    '90884',
                    '1010000050127',
                    '1010000043576',
                );
                $goods_image_list = array(
                    '1010000022707' => 'data/files/cool/jh/11.jpg',
                    '1010000027695' => 'data/files/cool/jh/12.jpg',
                    '1010000035956' => 'data/files/cool/jh/21.jpg',
                    '1010000046482' => 'data/files/cool/jh/22.jpg',
                    '1010000033110' => 'data/files/cool/jh/31.jpg',
                    '1010000048597' => 'data/files/cool/jh/32.jpg',
                    '1010000044457' => 'data/files/cool/jh/41.jpg',
                    '90884' => 'data/files/cool/jh/42.jpg',
                    '1010000050127' => 'data/files/cool/jh/51.jpg',
                    '1010000043576' => 'data/files/cool/jh/52.jpg',
                );
                break;
            default:
        }
        $sql = "
        SELECT 
            '{$ma_code}' as ma_code,
            -- [sa_id] => 1
            g.store_id,
            g.goods_id,
            '{$goods_type}' as goods_type,
            -- [sort] => 2
            -- [position] => 5
            '1' as status,
            '1306828800' as begin_time,
            '1416928800' as end_time,
            s.store_name,
            g.goods_name,
            g.price as goods_price,
            g.default_image as goods_image,
            g.sum_stock as goods_stock,
            g.if_show,
            g.closed,
            gs.views as goods_views,
            gs.sales as sales
            -- [mt_name] => 限时折
            FROM " . DB_PREFIX . "goods g
            LEFT JOIN " . DB_PREFIX . "store s
            ON s.store_id = g.store_id
            LEFT JOIN " . DB_PREFIX . "goods_statistics gs
            ON gs.goods_id = g.goods_id
            WHERE " . db_create_in($goods_id_list, 'g.goods_id') . "
        ";
        $list = $this->_marketing_activities_apply_mod->getAll($sql);

        $goods_list = array();
        foreach ($goods_id_list as $goods_id) {
            foreach ($list as $goods) {
                if ($goods['goods_id'] == $goods_id) {
                    if (!empty($goods_image_list[$goods_id])) {
                        $goods['goods_image'] = $goods_image_list[$goods_id];
                    }
                    $goods['sort'] = count($goods_list);
                    $goods['position'] = count($goods_list);
                    //若销售件数过少，则按一定规则进行伪造
                    if (intval($goods['sales']) < 3) {
                        $goods['sales'] = ((intval($goods['goods_id']) + intval($goods['sales'])) % 7) + 1;
                    }
                    $goods_list[] = $goods;
                    break;
                }
            }
        }

        return $goods_list;
    }

    /**取得酷公司相关展示数据 End********************************************************************************************************/

    /**上海购物节.抽奖 Start********************************************************************************************************/
    function sh_shopping()
    {
        include_once ROOT_PATH . '/apicomponent/php/app/activity.sh_shopping.php';
        $ss_obj = new sh_shopping($_GET);

        if (!isset($_GET['type']) || empty($_GET['type'])) {
            //http://1568.chinapay.cn/apicomponent/php/index.php?app=activity&key=1&act=sh_shopping&orderId=0000000010367069&orderDate=20110824&orderAmt=000000000001&mac=277eb5f06a66dcd8f5699af217b6fae2
            echo $ss_obj->lottery($this->visitor);
        } elseif (trim($_GET['type']) == "fill") {
            //http://1568.chinapay.cn/apicomponent/php/index.php?app=activity&act=sh_shopping&type=fill&real_name=james&id_card=no.1&tel=123456&ssul_id=1
            echo $ss_obj->save_user_info($this->visitor->get('user_id'));
        } elseif (trim($_GET['type']) == "list") {
            echo $ss_obj->get_user_lottery_list();
        } elseif (trim($_GET['type']) == "prize") {
            echo $ss_obj->get_prize_remain();
        } elseif (trim($_GET['type']) == "goods_past") {
            echo $ss_obj->get_goods_past();
        }
    }

    /**上海购物节.抽奖 End**********************************************************************************************************/


    /**
     * 发优惠券
     */
    function send_coupon()
    {

        if (empty($_REQUEST["coupon_id"])) {
            $this->echo_result("-1");
            exit;
        } else {
            $coupon_id = $_REQUEST["coupon_id"];
        }

        //TODO：检查是否发放过了

        $user_id = $this->visitor->get('user_id');

        if ($user_id <= 0) {
            $this->echo_result("-2");
            exit;
        }

        $template = array(
            //站内信配置
            'message_template' => array(
                'send' => false,
                'template' => "tobuyer_sh_shopping_lottery_notify",
            ),
            //邮件配置
            'mail_template' => array(
                'send' => false,
                'template' => "tobuyer_sh_shopping_lottery_notify",
            ),
            //手机短信配置
            'mobile_message_template' => array(
                'send' => false,
                'template' => "tobuyer_sh_shopping_lottery_notify",
            ),
        );
        $coupon_send = new SendCouponSimple(
            array(
                'coupon_id' => $coupon_id,
                'user' => $this->visitor,
                'mobile_code' => '',
                'lottery_level' => '',
            ),
            $template
        );
        $rst = $coupon_send->send_coupon();

        //等于8 是发送成功
        if ($rst == 8) {
            $this->echo_result(1);
            exit;
        } elseif ($rst == 3) {
            $this->echo_result("-3");
            exit;
        } else {
            $this->echo_result(0);
            exit;
        }

    }
}

?>
